package com.shtel.bss.saas.core.biz.common.vo;

import com.shtel.bss.saas.core.biz.common.annotation.IgnoreResponseAdvice;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @version Revision    1.0
 * @author: xieyonghua
 * @版权: 版权所有 (c) 2028
 * @创建日期: 2019-03-29 12:42
 * @功能说明: 统一返回值处理
 **/
@RestControllerAdvice
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {
    /**
     * 返回false 不处理
     *
     * @param methodParameter
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        if (methodParameter.getDeclaringClass().isAnnotationPresent(
                IgnoreResponseAdvice.class
        )) {
            return false;
        }
        if (methodParameter.getMethod().isAnnotationPresent(
                IgnoreResponseAdvice.class
        )) {
            return false;
        }

        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o,
                                  MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        RetResult<Object> response = RetResponse.makeOKRsp();
        if (null == o) {
            return response;
        } else if (o instanceof RetResult) {
            response = (RetResult<Object>) o;
        } else {
            response.setData(o);
        }
        //处理返回值是String的情况
//        if (o instanceof String) {
//            return JSON.toJSONString(response);
//        }
        return response;
    }


}
